package com.link.base.base.product.controller;

import com.link.base.base.product.model.ApiPriceList;
import com.link.base.base.product.model.PriceList;
import com.link.base.base.product.model.PriceListItem;
import com.link.base.base.product.service.ApiPriceListService;
import com.link.base.base.product.service.PriceListItemService;
import com.link.base.base.product.service.PriceListService;
import com.link.base.core.apiutils.ApiBeanUtils;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.aop.annotation.ApiStatusLog;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.service.BasicService;
import com.link.core.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/12 17:17
 */
@Controller("ApiPriceListController")
@RequestMapping("/link/api/price")
public class ApiPriceListController {

    @Resource
    private PriceListService priceListService;

    @Resource
    private ApiPriceListService apiPriceListService;

    @Resource
    private PriceListItemService priceListItemService;

    public BasicService<PriceList> getBasicService() throws Exception {
        return priceListService;
    }

    @RequestMapping(value = "/upsertHeadAndItem", method = RequestMethod.POST)
    @ResponseBody
    @ApiStatusLog(apiName = "新建或更新价格表", apiCode = "upsertPriceApi", url = "/api/price/upsertHeadAndItem")
    public Map<String, Object> upsertPriceAndItem(@RequestBody ApiPriceList apiPriceList) {
        Map<String, Object> result = new HashMap<>(4);
        Long crmId = null;
        try {
            crmId = apiPriceListService.upsertHeadAndItem(apiPriceList);
            ApiPriceList resultPriceList = getHeadAndItemOne(crmId, Long.parseLong(""));
            List<PriceListItem> priceListItemList = getPriceListItemList(crmId, apiPriceList.getPriceItemList());
            resultPriceList.setPriceItemList(priceListItemList);
            //crmId = upsertHeadAndItem(apiPriceList, request, response, session);
            result.put("crmId", crmId);
            result.put("result", resultPriceList);
            result.put("success", true);
            try {
                // auditTrailInsert(apiPriceList, request, session, "N");
            } catch (Exception e) {
                LCLogger.error().withMessageKey("upsertHeadAndItem")
                        .withMessage("审计追踪信息记录失败：" + e.getMessage()).flush();
                LCLogger.withException(e);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getPriceAndItem(@RequestParam Long crmId,
                                               HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            ApiPriceList resultPriceList = getHeadAndItem(crmId);
            result.put("result", resultPriceList);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    @RequestMapping("/getOne")
    @ResponseBody
    public Map<String, Object> getPriceAndItemOne(@RequestParam Long headId, @RequestParam Long itemId,
                                                  HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Map<String, Object> result = new HashMap<>(4);
        try {
            ApiPriceList resultPriceList = getHeadAndItemOne(headId, itemId);
            result.put("result", resultPriceList);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getMessage());
            LCLogger.withException(e);
        }
        return result;
    }

    /**
     * @param crmId
     * @param itemId
     * @return
     * @throws Exception
     * @最多只查询一条记录
     */
    private ApiPriceList getHeadAndItemOne(Long crmId, Long itemId) throws Exception {
        ApiPriceList resultPriceList = new ApiPriceList();
        ;
        if (crmId != null) {
            PriceList example = new PriceList();
            example.setId(crmId);
            example.setPageFlag(false);
            PriceList priceList = priceListService.queryById(example);
            if (priceList != null) {
                BeanUtils.copyProperties(priceList, resultPriceList);
                if (itemId != null) {
                    PriceListItem itemExample = new PriceListItem();
                    itemExample.setId(itemId);
                    PriceListItem priceListItem = priceListItemService.queryById(itemExample);
                    List<PriceListItem> itemList = new ArrayList<PriceListItem>();
                    itemList.add(priceListItem);
                    resultPriceList.setPriceItemList(itemList);
                }
            }
        }
        return resultPriceList;
    }

    /**
     * @author huanglongjian
     * @param crmPriceListId
     * @param list
     * @return
     * @throws Exception
     * @ 获取指定了行集成Id的记录
     */
    private List<PriceListItem> getPriceListItemList(Long crmPriceListId, List<PriceListItem> list) throws Exception {
        List<PriceListItem> priceListItemList = new ArrayList<PriceListItem>();
        if (null != list) {
            for (PriceListItem item : list) {
                if (!"".equals(item.getIntegrationId()) && item.getIntegrationId() != null) {
                    item.setPageFlag(false);
                    item.setTotalFlag(true);
                    item.setHeadId(crmPriceListId);
                    List<PriceListItem> priceListItemListInt = priceListItemService.queryByExamplePage(item);
                    if (priceListItemListInt != null) {
                        priceListItemList.add(priceListItemListInt.get(0));
                    }
                }
            }
        }
        return priceListItemList;
    }

    /**
     * 根据id查询价格表与价格表行数据l
     *
     * @param crmId
     * @return
     * @throws Exception
     */
    private ApiPriceList getHeadAndItem(Long crmId) throws Exception {
        ApiPriceList resultPriceList = null;
        if (crmId != null) {
            PriceList example = new PriceList();
            example.setId(crmId);
            example.setPageFlag(false);
            PriceList priceList = priceListService.queryById(example);
            if (priceList != null) {
                resultPriceList = new ApiPriceList();
                BeanUtils.copyProperties(priceList, resultPriceList);
                PriceListItem itemExample = new PriceListItem();
                itemExample.setPageFlag(false);
                itemExample.setHeadId(priceList.getId());
                List<PriceListItem> itemList = priceListItemService.queryByExamplePage(itemExample);
                resultPriceList.setPriceItemList(itemList);
            }
        }
        return resultPriceList;
    }

    /**
     * 新建或更新价格表头行
     *
     * @param apiPriceList
     * @param request
     * @param response
     * @param session
     * @return
     * @throws Exception
     */
    public Long upsertHeadAndItem(ApiPriceList apiPriceList, HttpServletRequest request,
                                    HttpServletResponse response, HttpSession session) throws Exception {


        Long crmId = null;
        if (StringUtils.isBlank(apiPriceList.getIntegrationId())) {
            throw new BasicControllerException("集成ID不能为空");
        }
        PriceList example = new PriceList();
        example.setIntegrationId(apiPriceList.getIntegrationId());
        example.setPageFlag(false);
        List<PriceList> list = priceListService.queryByExamplePage(example);
        if (list.size() > 1) {
            throw new BasicControllerException("根据价格表集成ID【" + apiPriceList.getIntegrationId() + "】找到多条记录");
        }

        if (list.size() == 0) {
            //头信息尚未新建，则全部数据新建
            PriceList priceList = new PriceList();
            ApiBeanUtils.copyProperties(apiPriceList, priceList);
            priceList.setId(null);
            priceListService.insert(priceList);
            List<PriceListItem> itemList = apiPriceList.getPriceItemList();
            if (itemList != null) {
                for (PriceListItem item : itemList) {
                    item.setHeadId(priceList.getId());
                    priceListItemService.insert(item);
                }
            }
            crmId = priceList.getId();
        } else if (list.size() == 1) {
            PriceList priceList = list.get(0);
            ApiBeanUtils.copyProperties(apiPriceList, priceList);
            priceListService.update(priceList);
            List<PriceListItem> itemList = apiPriceList.getPriceItemList();
            if (itemList != null) {
                PriceListItem itemExample = new PriceListItem();
                itemExample.setPageFlag(false);
                for (int i = 0; i < itemList.size(); i++) {
                    PriceListItem item = itemList.get(i);
                    String itemIntegrationId = item.getIntegrationId();
                    if (StringUtils.isBlank(itemIntegrationId)) {
                        throw new BasicControllerException("价格表行[" + i + "]集成ID不能为空");
                    }
                    itemExample.setIntegrationId(item.getIntegrationId());
                    List<PriceListItem> queryItemList = priceListItemService.queryByExamplePage(itemExample);
                    if (queryItemList.size() > 1) {
                        throw new BasicControllerException("根据价格行[" + i + "]集成ID【" + itemIntegrationId + "】找到多条记录");
                    } else if (queryItemList.size() == 0) {
                        item.setHeadId(priceList.getId());
                        item.setId(null);
                        priceListItemService.insert(item);
                    } else if (queryItemList.size() == 1) {
                        PriceListItem queryItem = queryItemList.get(0);
                        if (!priceList.getId().equals(queryItem.getHeadId())) {
                            throw new BasicControllerException("根据价格行[" + i + "]集成ID【" + itemIntegrationId + "】找到"
                                    + "记录的关联的价格表ID与当前价格表ID不符");
                        }
                        ApiBeanUtils.copyProperties(item, queryItem);
                        priceListItemService.update(item);
                    }
                }
            }
            crmId = priceList.getId();
        }
        return crmId;
    }
}
